package com.szrt.scott.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * 处理文件上传的Servlet
 */
@WebServlet("/upload.do")
@MultipartConfig
public class UpLoadFileServlet extends HttpServlet{
	private static final long serialVersionUID = 1912833052633883732L;


	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取文件部件part
		Part part = req.getPart("uploadfile");
		
		//获取文件服务器头部信息
		String root = req.getServletContext().getRealPath("/upload2");
		String name = part.getHeader("content-disposition");
		String ext = name.substring(name.lastIndexOf("."),name.length()-1);
		
		//防止中文的问题
		String filename = root +"/"+UUID.randomUUID().toString()+ext;
		System.out.println(filename);
		int index  = filename.lastIndexOf("upload2");
		String fn = filename.substring(index+8);
		req.setAttribute("fn", fn);
		System.out.println(fn);
		part.write(filename);
		
		req.getRequestDispatcher("/success.jsp").forward(req, resp);
	}
}
